<template>
  <div>
    <card-mysql-setup :enable="!isMysqlAvailable" @done="actionMysqlSetupDone"></card-mysql-setup>
    <el-card v-if="isMysqlAvailable" class="box-card" style="margin-bottom:10px;position:relative;">
      <div slot="header" class="clearfix">
        <span>数据库列表</span>
        <el-button style="float: right;" size="mini" @click="actionRefreshList">刷新</el-button>
        <el-button style="float: right;margin-right:10px;" size="mini" @click="actionCreate">新建</el-button>
      </div>
      
      <el-table :data="databases" style="width: 100%">
        <el-table-column prop="name" label="名称" width="200"></el-table-column>
        <el-table-column label="空间">
          <template slot-scope="scope">
            <span>表：{{scope.row.tableCount}}</span> &nbsp;
            <span>数据：{{(scope.row.dataLength/1024/1024).toFixed(2)}}MB</span> &nbsp;
            <span>索引：{{(scope.row.indexLength/1024/1024).toFixed(2)}}MB</span> &nbsp;
          </template>
        </el-table-column>
        <el-table-column align="right" label="操作">
          <template slot-scope="scope">
            <el-button size="mini" @click="actionDatabaseView(scope.row.name)">查看</el-button>
            <el-button size="mini" @click="actionDatabaseQuery(scope.row.name)">查询</el-button>
            <el-button size="mini" @click="actionDatabaseDrop(scope.row.name)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <mysql-database-create-dialog ref="dialogCreate" @created="actionRefreshList"></mysql-database-create-dialog>
    <mysql-database-query-dialog ref="dialogQuery"></mysql-database-query-dialog>
    <mysql-database-view-dialog ref="dialogView"></mysql-database-view-dialog>
  </div>
</template>
<script>
import CardMysqlSetup from './CardMysqlSetup.vue'
import MysqlConnection from './MysqlConnection.js'
import MysqlDatabaseViewDialog from './MysqlDatabaseViewDialog.vue'
import MysqlDatabaseQueryDialog from './MysqlDatabaseQueryDialog.vue'
import MysqlDatabaseCreateDialog from './MysqlDatabaseCreateDialog.vue'
export default {
    name : 'MysqlDatabaseList',
    components : {
        'card-mysql-setup' : CardMysqlSetup,
        'mysql-database-create-dialog' : MysqlDatabaseCreateDialog,
        'mysql-database-query-dialog' : MysqlDatabaseQueryDialog,
        'mysql-database-view-dialog' : MysqlDatabaseViewDialog,
    },
    data() {
        return {
            isMysqlAvailable : true,
            connection : null,
            databases : [],
        };
    },
    async mounted() {
        this.connectToDatabase();
    },
    destroyed() {
        this.connection.disconnect();
    },
    methods : {
        // 数据库安装完成后的回调
        actionMysqlSetupDone() {
            this.isMysqlAvailable = true;
            this.connectToDatabase();
        },

        // 连接到数据库
        async connectToDatabase() {
            let server = this.$store.getters.serverCurrent;
            let config = await server.getConfiguration('mysql');
            if ( null == config ) {
                this.isMysqlAvailable = false;
                return;
            }

            this.connection = new MysqlConnection({
                host     : config.host,
                user     : config.user,
                password : config.password,
                database : config.database
            });
            await this.actionRefreshList();
        },

        // 打开数据库对话框
        actionCreate() {
            this.$refs.dialogCreate.open(this.connection);
        },

        // 刷新列表
        async actionRefreshList() {
            this.databases = [];
            
            let dblist = {};
            let dbnames = await this.connection.execute('show databases');
            for ( let i=0; i<dbnames.length; i++ ) {
                dblist[dbnames[i]['Database']] = {
                    name : dbnames[i]['Database'],
                    dataLength : 0,
                    indexLength : 0,
                    tableCount : 0,
                };
            }

            let sql = `
                SELECT 
                  TABLE_SCHEMA AS \`db_name\`, 
                  SUM(DATA_LENGTH) AS \`data_length\`, 
                  SUM(INDEX_LENGTH) AS \`index_length\`, 
                  COUNT(TABLE_NAME) AS \`table_count\` 
                FROM \`information_schema\`.\`TABLES\` 
                GROUP BY TABLE_SCHEMA
            `;
            let databases = await this.connection.execute(sql);
            for ( let i=0; i<databases.length; i++ ) {
                let dbname = databases[i].db_name;
                dblist[dbname] = {
                    name : databases[i].db_name,
                    dataLength : databases[i].data_length,
                    indexLength : databases[i].index_length,
                    tableCount : databases[i].table_count,
                };
            }
            
            this.databases = Object.values(dblist);
        },

        // 数据库删除
        async actionDatabaseDrop( name ) {
            try {
                await this.$confirm(`此操作将删除数据库 ${name}, 是否继续?`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                });
            } catch {
                return;
            }
            
            let sql = `DROP DATABASE \`${name}\``;
            try {
                await this.connection.execute(sql);
            } catch ( e ) {
                this.$message.error(e.message);
                return;
            }

            await this.actionRefreshList();
        },

        // 数据库查询
        actionDatabaseQuery( name ) {
            this.$refs.dialogQuery.open(this.connection, name);
        },

        // 数据库查看 
        actionDatabaseView( name ) {
            this.$refs.dialogView.open(this.connection, name);
        },
    }
}
</script>